package com.zhentao.controller;

import com.zhentao.service.impl.MinioService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 图片和视频上传控制器
 */
@RestController
@RequestMapping("/api/upload")
@CrossOrigin(origins = "*")
public class ImageUploadController {

    @Autowired
    private MinioService minioService;

    /**
     * 测试MinIO连接
     */
    @GetMapping("/test")
    public ResponseEntity<Map<String, Object>> testMinioConnection() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            minioService.testConnection();
            result.put("success", true);
            result.put("message", "MinIO连接正常");
            result.put("data", null);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "MinIO连接失败: " + e.getMessage());
            result.put("data", null);
            
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 获取文件信息
     * @param objectName 对象名称
     * @return 文件信息
     */
    @GetMapping("/file-info")
    public ResponseEntity<Map<String, Object>> getFileInfo(
            @RequestParam("objectName") String objectName) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            Map<String, Object> fileInfo = minioService.getFileInfo(objectName);
            
            result.put("success", true);
            result.put("message", "获取文件信息成功");
            result.put("data", fileInfo);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取文件信息失败: " + e.getMessage());
            result.put("data", null);
            
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 获取文件的预签名URL
     * @param objectName 对象名称
     * @param expiry 过期时间（秒，默认3600）
     * @return 预签名URL
     */
    @GetMapping("/presigned-url")
    public ResponseEntity<Map<String, Object>> getPresignedUrl(
            @RequestParam("objectName") String objectName,
            @RequestParam(value = "expiry", defaultValue = "3600") int expiry) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            String presignedUrl = minioService.getPresignedUrl(objectName, expiry);
            
            result.put("success", true);
            result.put("message", "获取预签名URL成功");
            result.put("data", presignedUrl);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取预签名URL失败: " + e.getMessage());
            result.put("data", null);
            
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 上传单个视频
     * @param file 视频文件
     * @param folder 文件夹路径（可选）
     * @return 上传结果
     */
    @PostMapping("/video")
    public ResponseEntity<Map<String, Object>> uploadVideo(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "folder", required = false) String folder) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证文件大小（限制为500MB）
            if (file.getSize() > 500 * 1024 * 1024) {
                result.put("success", false);
                result.put("message", "视频文件大小不能超过500MB");
                result.put("data", null);
                return ResponseEntity.badRequest().body(result);
            }
            
            String videoUrl = minioService.uploadVideo(file, folder);
            
            result.put("success", true);
            result.put("message", "视频上传成功");
            result.put("data", videoUrl);
            result.put("fileType", "video");
            result.put("fileSize", file.getSize());
            result.put("originalName", file.getOriginalFilename());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "视频上传失败: " + e.getMessage());
            result.put("data", null);
            
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 上传单张图片
     * @param file 图片文件
     * @param folder 文件夹路径（可选）
     * @return 上传结果
     */
    @PostMapping("/image")
    public ResponseEntity<Map<String, Object>> uploadImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "folder", required = false) String folder) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            String imageUrl = minioService.uploadImage(file, folder);
            
            result.put("success", true);
            result.put("message", "图片上传成功");
            result.put("data", imageUrl);
            result.put("fileType", "image");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "图片上传失败: " + e.getMessage());
            result.put("data", null);
            
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 通用文件上传（支持图片和视频）
     * @param file 文件
     * @param folder 文件夹路径（可选）
     * @return 上传结果
     */
    @PostMapping("/file")
    public ResponseEntity<Map<String, Object>> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "folder", required = false) String folder) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            String contentType = file.getContentType();
            String fileType = "unknown";
            
            if (contentType != null) {
                if (contentType.startsWith("image/")) {
                    fileType = "image";
                } else if (contentType.startsWith("video/")) {
                    fileType = "video";
                    // 视频文件大小限制
                    if (file.getSize() > 500 * 1024 * 1024) {
                        result.put("success", false);
                        result.put("message", "视频文件大小不能超过500MB");
                        result.put("data", null);
                        return ResponseEntity.badRequest().body(result);
                    }
                } else {
                    result.put("success", false);
                    result.put("message", "不支持的文件类型，请上传图片或视频文件");
                    result.put("data", null);
                    return ResponseEntity.badRequest().body(result);
                }
            }
            
            String fileUrl = minioService.uploadFile(file, folder, "any");
            
            result.put("success", true);
            result.put("message", fileType + "上传成功");
            result.put("data", fileUrl);
            result.put("fileType", fileType);
            result.put("fileSize", file.getSize());
            result.put("originalName", file.getOriginalFilename());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "文件上传失败: " + e.getMessage());
            result.put("data", null);
            
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 批量上传视频
     * @param files 视频文件数组
     * @param folder 文件夹路径（可选）
     * @return 上传结果
     */
    @PostMapping("/videos/batch")
    public ResponseEntity<Map<String, Object>> uploadBatchVideos(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam(value = "folder", required = false) String folder) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            String[] videoUrls = new String[files.length];
            
            for (int i = 0; i < files.length; i++) {
                if (files[i].getSize() > 500 * 1024 * 1024) {
                    result.put("success", false);
                    result.put("message", "第" + (i + 1) + "个视频文件大小超过500MB限制");
                    result.put("data", null);
                    return ResponseEntity.badRequest().body(result);
                }
                
                videoUrls[i] = minioService.uploadVideo(files[i], folder);
            }
            
            result.put("success", true);
            result.put("message", "批量视频上传成功");
            result.put("data", videoUrls);
            result.put("fileType", "video");
            result.put("count", files.length);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量视频上传失败: " + e.getMessage());
            result.put("data", null);
            
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 批量上传图片
     * @param files 图片文件数组
     * @param folder 文件夹路径（可选）
     * @return 上传结果
     */
    @PostMapping("/images/batch")
    public ResponseEntity<Map<String, Object>> uploadBatchImages(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam(value = "folder", required = false) String folder) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            String[] imageUrls = new String[files.length];
            
            for (int i = 0; i < files.length; i++) {
                imageUrls[i] = minioService.uploadImage(files[i], folder);
            }
            
            result.put("success", true);
            result.put("message", "批量图片上传成功");
            result.put("data", imageUrls);
            result.put("fileType", "image");
            result.put("count", files.length);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量图片上传失败: " + e.getMessage());
            result.put("data", null);
            
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 删除文件
     * @param objectName 对象名称
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    public ResponseEntity<Map<String, Object>> deleteFile(
            @RequestParam("objectName") String objectName) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            minioService.deleteFile(objectName);
            
            result.put("success", true);
            result.put("message", "文件删除成功");
            result.put("data", null);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "文件删除失败: " + e.getMessage());
            result.put("data", null);
            
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 面诊图片上传接口
     * @param file 面诊图片文件
     * @param fileName 自定义文件名（可选）
     * @param bucketName 自定义存储桶（可选）
     * @return 上传结果
     */
    @PostMapping("/faceImage")
    public ResponseEntity<Map<String, Object>> uploadFaceImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "fileName", required = false) String fileName,
            @RequestParam(value = "bucketName", required = false) String bucketName) {
        
        Map<String, Object> result = new HashMap<>();
        
        if (file.isEmpty()) {
            result.put("code", 400);
            result.put("message", "文件为空");
            result.put("data", null);
            return ResponseEntity.badRequest().body(result);
        }
        
        try {
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                result.put("code", 400);
                result.put("message", "请上传图片文件");
                result.put("data", null);
                return ResponseEntity.badRequest().body(result);
            }
            
            // 使用自定义bucket或默认bucket
            String targetBucket = bucketName != null ? bucketName : "zyai";
            
            // 生成文件名
            if (fileName == null || fileName.isEmpty()) {
                String originalFilename = file.getOriginalFilename();
                String extension = originalFilename != null ? 
                    originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";
                fileName = "face_" + System.currentTimeMillis() + "_" + 
                    java.util.UUID.randomUUID().toString().substring(0, 8) + extension;
            }
            
            // 上传到MinIO
            String imageUrl = minioService.uploadFileWithCustomName(file, "face-diagnosis", fileName);
            
            result.put("code", 200);
            result.put("message", "面诊图片上传成功");
            Map<String, String> data = new HashMap<>();
            data.put("fileName", fileName);
            data.put("imageUrl", imageUrl);
            result.put("data", data);
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "面诊图片上传失败: " + e.getMessage());
            result.put("data", null);
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 舌诊图片上传接口
     * @param file 舌诊图片文件
     * @param fileName 自定义文件名（可选）
     * @param bucketName 自定义存储桶（可选）
     * @return 上传结果
     */
    @PostMapping("/tongueImage")
    public ResponseEntity<Map<String, Object>> uploadTongueImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "fileName", required = false) String fileName,
            @RequestParam(value = "bucketName", required = false) String bucketName) {
        
        Map<String, Object> result = new HashMap<>();
        
        if (file.isEmpty()) {
            result.put("code", 400);
            result.put("message", "文件为空");
            result.put("data", null);
            return ResponseEntity.badRequest().body(result);
        }
        
        try {
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                result.put("code", 400);
                result.put("message", "请上传图片文件");
                result.put("data", null);
                return ResponseEntity.badRequest().body(result);
            }
            
            // 使用自定义bucket或默认bucket
            String targetBucket = bucketName != null ? bucketName : "zyai";
            
            // 生成文件名
            if (fileName == null || fileName.isEmpty()) {
                String originalFilename = file.getOriginalFilename();
                String extension = originalFilename != null ? 
                    originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";
                fileName = "tongue_" + System.currentTimeMillis() + "_" + 
                    java.util.UUID.randomUUID().toString().substring(0, 8) + extension;
            }
            
            // 上传到MinIO
            String imageUrl = minioService.uploadFileWithCustomName(file, "tongue-diagnosis", fileName);
            
            result.put("code", 200);
            result.put("message", "舌诊图片上传成功");
            Map<String, String> data = new HashMap<>();
            data.put("fileName", fileName);
            data.put("imageUrl", imageUrl);
            result.put("data", data);
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "舌诊图片上传失败: " + e.getMessage());
            result.put("data", null);
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 健康检查接口
     * @return 服务状态
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "服务正常");
        result.put("timestamp", System.currentTimeMillis());
        result.put("service", "wx_banner");
        return ResponseEntity.ok(result);
    }

    /**
     * 检查文件是否存在
     * @param objectName 对象名称
     * @return 检查结果
     */
    @GetMapping("/exists")
    public ResponseEntity<Map<String, Object>> checkFileExists(
            @RequestParam("objectName") String objectName) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean exists = minioService.fileExists(objectName);
            
            result.put("success", true);
            result.put("message", "检查完成");
            result.put("data", exists);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "检查失败: " + e.getMessage());
            result.put("data", null);
            
            return ResponseEntity.badRequest().body(result);
        }
    }
} 